// test/pages/buyTicket/buyTicket.js
const app = getApp();
var WxParse = require("../../../wxParse/wxParse.js")
var request = require('../../../utils/api.js');
var api = require("../../../utils/api.js")
Page({

    /**
     * 页面的初始数据
     */
    data: {
        sid: 0,
        com_id: "",
        tid: 0,
        goodsNum: 1,
        ticketInfo: {},
        showModal: false,
        codeText: "",
        com_ticket_info_times: [],
        com_ticket_info_type: [],
        countDownDay: "",
        countDownHour: "",
        countDownMinute: "",
        countDownSecond: "",
        startSign:false
    },
    inputText(e) {
        this.setData({
            codeText: e.detail.value
        })
    },
    checkIsValid() {
        this.setData({
            showModal: true
        })
    },
    // 弹出层取消
    cancel() {
        this.setData({
            showModal: false
        })
    },
    async confirmTrue() {
        // console.log(111111111111111111);
        // const res = await request.fetchApi("Ticket/check_code", {
        //     com_id: this.data.com_id,
        //     code: this.data.codeText
        // })
        wx.request({
            url: app.globalData.host + "Ticket/check_code",
            data: {
                com_id: this.data.com_id,
                code: this.data.codeText
            },
            success: (res) => {
                if (res.data.code == 2000) {
                    this.setData({
                        showModal: false
                    })
                    wx.showToast({
                        title: res.data.msg,
                        icon: "none",
                        mask: true
                    })
                    setTimeout(() => {
                        wx.navigateTo({
                            url: `/test/pages/check_ticket/check_ticket?com_id=${this.data.com_id}&code=${this.data.codeText}`
                        });
                    }, 1000);
                } else {
                    wx.showToast({
                        title: res.data.msg,
                        mask: true,
                        icon: "none"
                    })
                }
            },
            fail(err) {
                console.log(err);
            }
        })

    },
    // 
    reduceNum() {
        if (this.data.goodsNum === 1) return;
        this.setData({
            goodsNum: --this.data.goodsNum
        })
    },
    addNum() {
        this.setData({
            goodsNum: ++this.data.goodsNum,
        })

    },
    getTicketData(com_id) {
        wx.request({
            url: app.globalData.host + 'Ticket/ticket_info',
            data: {
                com_id,
                token: wx.getStorageSync('token') || '',
            },
            method: 'POST',
            success: (res) => {
                wx.stopPullDownRefresh()
                if (res.data.code === 2000) {
                    // console.log(res.data.data);
                    WxParse.wxParse('article', 'html', res.data.data[0].com_info.ticket_notice, this, 25);
                    this.setData({
                        ticketInfo: res.data.data[0],
                        com_ticket_info_times: res.data.data[0].com_ticket_info_times,
                        com_ticket_info_type: res.data.data[0].com_ticket_info_type,
                        sid: res.data.data[0].com_ticket_info_type[0].id,
                        tid: res.data.data[0].com_ticket_info_times[0].id,
                    })
                    this.countime(res.data.data[0].com_info.apply_start_time)
                    // this.countime("2021-03-25T20:00:00")
                } else {
                    wx.navigateBack()
                    setTimeout(() => {
                        wx.showToast({
                            title: res.data.msg,
                            icon: 'none',
                            duration: 1500,
                        })
                    }, 500)
                }
            },
            fail(err) {
                console.log(err)
            }
        })
    },
    // 选择场次
    async selectTimes(e) {
        this.setData({
            sid: e.currentTarget.dataset.sid,
            goodsNum: 1
        })
        try {
            const res = await request.fetchApi("Ticket/get_type", {
                com_id: this.data.com_id,
                times: e.currentTarget.dataset.name
            })
            this.setData({
                com_ticket_info_type: res,
                tid: res[0].id
            })
        } catch (error) {
            console.log(error);
        }

    },
    selectTicket(e) {
        this.setData({
            tid: e.currentTarget.dataset.tid,
            goodsNum: 1
        })
    },
    handleClick(e) {
        wx.navigateTo({
            url: `/test/pages/check_ticket_order/check_ticket_order?order_id=${this.data.ticketInfo.ticket_order[e.currentTarget.id].order_no}`
        })
    },
    // 客服
    call() {
        wx.makePhoneCall({
            phoneNumber: this.data.ticketInfo.com_info.major,
        })
    },

    // 报名
    signTrain() {
        const that = this
        if (!this.data.goodsNum) {
            wx.showToast({
                title: '数量不能为0',
                icon: "none"
            })
            return
        }
        if (!wx.getStorageSync("token")) {
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            })
            setTimeout(() => {
                wx.switchTab({
                    url: '/pages/personal/personal',
                })
            }, 1000);
            return
        }
        const currentType = this.data.com_ticket_info_type.filter(item => {
            return item.id === this.data.tid
        })
        wx.request({
            url: app.globalData.host + 'Ticket/pay_check',
            data: {
                token: wx.getStorageSync("token"),
                com_id: this.data.com_id,
                ticket_id: this.data.tid,
                price: currentType[0].price * this.data.goodsNum,
                num: this.data.goodsNum
            },
            success(res) {
                if (res.data.code === 2000) {
                    wx.navigateTo({
                        url: `/test/pages/ticketPayInfo/ticketPayInfo?tid=${that.data.tid}&sid=${that.data.sid}&com_id=${that.data.com_id}&nums=${that.data.goodsNum}&ticketPrice=${currentType[0].price * that.data.goodsNum}`,
                    })
                } else {
                    wx.showToast({
                        title: res.data.msg,
                        icon: "none"
                    })
                }
            },
            fail(err) {
                console.log(err);
            }
        })


    },
    // 获取截止时间
    countime(date) {
        var totalSecond = Date.parse(new Date(date)) / 1000 - Date.parse(new Date()) / 1000;
        if(totalSecond < 0){
            this.setData({
                startSign:true
            })
            return
        }
        var interval = setInterval(function () {
            // 秒数
            var second = totalSecond;
            // 天数位
            var day = Math.floor(second / 3600 / 24);
            var days = day.toString();
            if (days.length == 1) days = '0' + days;
            // 小时位
            var hr = Math.floor((second - day * 3600 * 24) / 3600);
            var hours = hr.toString();
            if (hours.length == 1) hours = '0' + hours;
            // 分钟位
            var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
            var minutes = min.toString();
            if (minutes.length == 1) minutes = '0' + minutes;
            // 秒位
            var sec = second - day * 3600 * 24 - hr * 3600 - min * 60;
            var senonds = sec.toString();
            if (senonds.length == 1) senonds = '0' + senonds;
            this.setData({
                countDownDay: days,
                countDownHour: hours,
                countDownMinute: minutes,
                countDownSecond: senonds,
            });
            totalSecond--;
            if (totalSecond < 0) {
                clearInterval(interval);
                wx.showToast({
                    title: '报名开始',
                    icon: 'none'
                });
                this.setData({
                    countDownDay: '00',
                    countDownHour: '00',
                    countDownMinute: '00',
                    countDownSecond: '00',
                    startSign: true
                });
            }
        }.bind(this), 1000);
    },
    onLoad: function (options) {

        this.setData({
            com_id: options.id,
            // com_id: 27
        })
        this.getTicketData(this.data.com_id)

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        this.getTicketData(this.data.com_id)
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})